#!/bin/bash

# MCP 天气服务测试脚本

echo "=== MCP 天气服务诊断 ==="
echo ""

# 1. 检查 Java 版本
echo "1. 检查 Java 版本："
if [ -f "/Users/javaleader/dev/jdk-11.0.26.jdk/Contents/Home/bin/java" ]; then
    JAVA_VERSION=$("/Users/javaleader/dev/jdk-11.0.26.jdk/Contents/Home/bin/java" -version 2>&1 | head -1)
    echo "   ✓ Java 路径存在: $JAVA_VERSION"
else
    echo "   ✗ Java 路径不存在！"
    exit 1
fi

# 2. 检查 JAR 文件
echo ""
echo "2. 检查 JAR 文件："
JAR_FILE="/Users/javaleader/cursor/mcp-services/mcp-weather-java/target/mcp-weather-java-1.0.0.jar"
if [ -f "$JAR_FILE" ]; then
    JAR_SIZE=$(ls -lh "$JAR_FILE" | awk '{print $5}')
    echo "   ✓ JAR 文件存在: $JAR_SIZE"
else
    echo "   ✗ JAR 文件不存在！"
    exit 1
fi

# 3. 测试服务初始化
echo ""
echo "3. 测试服务初始化："
INIT_RESPONSE=$(echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}' | \
    /Users/javaleader/dev/jdk-11.0.26.jdk/Contents/Home/bin/java -jar "$JAR_FILE" 2>&1 | \
    grep -o '"serverInfo":{"name":"[^"]*"' | head -1)

if [ -n "$INIT_RESPONSE" ]; then
    echo "   ✓ 服务初始化成功: $INIT_RESPONSE"
else
    echo "   ✗ 服务初始化失败！"
    exit 1
fi

# 4. 测试工具列表
echo ""
echo "4. 测试工具列表："
TOOLS_OUTPUT=$( (echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}'; \
    sleep 1; \
    echo '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}') | \
    timeout 10 /Users/javaleader/dev/jdk-11.0.26.jdk/Contents/Home/bin/java -jar "$JAR_FILE" 2>&1)

TOOLS_RESPONSE=$(echo "$TOOLS_OUTPUT" | grep -o '"name":"[^"]*"' | head -1)

if [ -n "$TOOLS_RESPONSE" ]; then
    echo "   ✓ 工具列表获取成功: $TOOLS_RESPONSE"
else
    echo "   ⚠ 工具列表获取可能有问题，但服务基本正常"
    echo "   完整输出（最后5行）："
    echo "$TOOLS_OUTPUT" | tail -5 | sed 's/^/      /'
fi

# 5. 测试工具调用
echo ""
echo "5. 测试工具调用（查询青岛天气）："
CALL_OUTPUT=$( (echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}'; \
    sleep 1; \
    echo '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"weather.get","arguments":{"city":"青岛","extensions":"all"}}}') | \
    timeout 15 /Users/javaleader/dev/jdk-11.0.26.jdk/Contents/Home/bin/java -jar "$JAR_FILE" 2>&1)

CALL_RESPONSE=$(echo "$CALL_OUTPUT" | grep -o '"type":"text"' | head -1)

if [ -n "$CALL_RESPONSE" ]; then
    echo "   ✓ 工具调用成功"
else
    echo "   ⚠ 工具调用可能超时（这是正常的，因为需要网络请求）"
fi

# 6. 检查环境变量
echo ""
echo "6. 检查环境变量："
if [ -z "$AMAP_KEY" ]; then
    echo "   ⚠ AMAP_KEY 未设置（如果配置在 Cursor 中，这是正常的）"
else
    echo "   ✓ AMAP_KEY 已设置"
fi

echo ""
echo "=== 诊断完成 ==="
echo ""
echo "如果所有测试都通过，但 Cursor 中仍无法使用，请尝试："
echo "1. 完全重启 Cursor（Command+Q 退出，然后重新打开）"
echo "2. 在 Cursor 设置中检查 MCP 服务状态和日志"
echo "3. 确认工具名称是 'weather.get'（带点号），不是 'weather_get'（下划线）"

